﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;

namespace HttpHelper
{
    public class HttpClientService
    {
        private static HttpClientService? _instance;

        private static readonly object _lock = new object();

        private static HttpClient _client = new HttpClient();

        public HttpClientService() { }

        public static HttpClientService GetInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new HttpClientService();
                    }

                    if (_client is null)
                    {
                        _client = new HttpClient();
                    }
                }
            }
            return _instance;
        }

        /// <summary>
        /// HttpClient Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public string HttpGet(string url)
        {
            try
            {
                if (_client.BaseAddress is null)
                {
                    _client.BaseAddress = new Uri(url);
                }

                _client.DefaultRequestHeaders.Accept.Clear();
                HttpResponseMessage response = _client.GetAsync(url).Result;

                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;

                return responseBody;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        /// <summary>
        /// HttpClient Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="content">HttpContent</param>
        /// <returns></returns>
        public string HttpPost(string url, string content, string? token = null)
        {
            try
            {
                if (_client.BaseAddress is null)
                {
                    _client.BaseAddress = new Uri(url);
                }

                // System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

                _client.DefaultRequestHeaders.Accept.Clear();
                _client.DefaultRequestHeaders.Connection.Add("keep-alive");
                if (!string.IsNullOrEmpty(token))
                {
                    _client.DefaultRequestHeaders.Add("Authorization-Token", token);
                }
                _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = _client.PostAsync(url, new StringContent(content, Encoding.UTF8, "application/json")).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;

                return responseBody;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        /// <summary>
        /// HttpClient Post请求
        /// </summary>
        /// <remarks>
        /// 用于非正常http请求
        /// </remarks>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public string HttpPost(string url, string content)
        {
            try
            {
                using (var request = new HttpRequestMessage(new HttpMethod("Post"), url))
                {
                    // System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

                    request.Headers.TryAddWithoutValidation("Content-Type", "application/json");

                    request.Content = new StringContent(content);

                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                    var response = _client.SendAsync(request).Result;
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        //public string GetUriParam(object obj, string url = "")
        //{
        //    PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append(url);
        //    sb.Append("?");
        //    foreach (var p in propertis)
        //    {
        //        var v = p.GetValue(obj, null);
        //        if (v == null) continue;

        //        sb.Append(p.Name);
        //        sb.Append("=");
        //        sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
        //        sb.Append("&");
        //    }
        //    sb.Remove(sb.Length - 1, 1);

        //    return sb.ToString();
        //}
    }
}
